package com.example.service.impl;


import com.example.dao.UserAccessDAO;
import com.example.databean.LoginParam;
import com.example.databean.UserParam;
import com.example.service.UserInfoService;
import com.example.vo.UserAccess;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;



@Service
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserAccessDAO userAccessDAO;


    @Override
    public UserAccess login(LoginParam loginParam) {
        try {
            UserAccess userAccess = userAccessDAO.findTopByUserIdOrPhone(loginParam.getUserId(), loginParam.getUserId());

            log.info("User Access: {}", userAccess);
            return userAccess;

        } catch (Exception e) {
            return null;
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(UserParam userParam) {

        try {
            //注册
            UserAccess userAccess = new UserAccess();
            BeanUtils.copyProperties(userParam, userAccess);
            userAccessDAO.save(userAccess);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }


    @Override
    public UserAccess getUserInfoByUserIdOrPhone(String checkUser) {
        try {
            UserAccess userAccess = userAccessDAO.findTopByUserIdOrPhone(checkUser, checkUser);

            log.info("User Access: {}", userAccess);
            return userAccess;

        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public UserAccess getUserInfoByUserId(String userId) {

        try {
            UserAccess userAccess = userAccessDAO.findByUserId(userId);

            log.info("User Access: {}", userAccess);
            return userAccess;

        } catch (Exception e) {
            return null;
        }

    }



    @Override
    public Page<UserAccess> getAllUserInfo(Pageable pageable, String keyword) {
        if(StringUtils.hasText(keyword)){
            return userAccessDAO.findAllUserByPageAndKeyword(pageable, keyword);
        }else {
            return userAccessDAO.findAllUserByPage(pageable);
        }
    }
}
